package lv.solcraft.replication.server.api;

import java.util.List;

import lv.solcraft.replication.server.bdb.Database;
import lv.solcraft.replication.server.bdb.TxTemplateNoResult;
import lv.solcraft.replication.server.dao.OperDataAccess;
import lv.solcraft.replication.server.model.Oper;
import lv.solcraft.replication.server.model.OperSite;
import lv.solcraft.replication.server.model.OperStateUpdate;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sleepycat.je.Transaction;

@Service
public class UpdateOperStatesCommand {

    private static final Logger log = Logger.getLogger(UpdateOperStatesCommand.class);

    private final Database database;
    private OperDataAccess operDataAccess;

    @Autowired
    public UpdateOperStatesCommand(Database database) {
        this.database = database;
        this.operDataAccess = database.getOperDataAccess();
    }

    public final void updateStates(final List<OperStateUpdate> operStates) {
        for (final OperStateUpdate stateUpdate : operStates) {
            new TxTemplateNoResult(database, 10) {
                @Override
                protected void executeInTxNoResult(Transaction tx) throws Exception {
                    updateState(stateUpdate);
                }
            }.execute();
        }
    }

    protected void updateState(OperStateUpdate stateUpdate) {
        Oper oper = operDataAccess.find(stateUpdate.getOperId());
        if (oper == null) {
            log.warn("Trying to update oper state for non-existing oper, " + stateUpdate);
            return;
        }
        oper.deleteStates(stateUpdate.getSiteId());
        OperSite operSite = oper.createOperSite(stateUpdate.getSiteId(), stateUpdate.getState());
        operSite.setMessage(stateUpdate.getMessage());
        operSite.persist();
    }

}
